<?php
header("Content-Type: application/json; charset=utf-8");

$servername = "localhost";
$username = "";
$password = "";
$dbname = "";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die(json_encode(["error" => "Database connection failed: " . $conn->connect_error]));
}
$conn->set_charset("utf8");

$data = file_get_contents("php://input");
$hotinfo = json_decode($data, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    die(json_encode(["error" => "Invalid JSON data: " . json_last_error_msg()]));
}

$id = isset($hotinfo['id']) ? (int)$hotinfo['id'] : null;
$option = isset($hotinfo['option']) ? $hotinfo['option'] : '';

if ($id === null || !in_array($option, ['like', 'unlike'])) {
    die(json_encode(["error" => "Missing or invalid parameters"]));
}
$conn->begin_transaction();

try {
    $checkStmt = $conn->prepare("SELECT eventid FROM show_event WHERE eventid = ?");
    $checkStmt->bind_param("i", $id);
    $checkStmt->execute();
    $result = $checkStmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception("Record not found");
    }
    $checkStmt->close();
    
    if ($option === 'like') {
        $updateStmt = $conn->prepare("UPDATE show_event SET hot = hot + 1 WHERE eventid = ?");
    } else {
        $updateStmt = $conn->prepare("UPDATE show_event SET hot = GREATEST(hot - 1, 0) WHERE eventid = ?");
    }
    
    $updateStmt->bind_param("i", $id);
    
    if (!$updateStmt->execute()) {
        throw new Exception("Database error: " . $updateStmt->error);
    }
    
    $affectedRows = $updateStmt->affected_rows;
    $updateStmt->close();
    
    if ($affectedRows === 0) {
        throw new Exception("Update failed or no changes made");
    }
    
    $conn->commit();
    echo json_encode(["message" => "Operation successful", "option" => $option]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(["error" => $e->getMessage()]);
}

$conn->close();
?>